#include "workthread.h"
#include <QHostAddress>
WorkThread::WorkThread(qintptr socket) : m_socket(socket) {
  qDebug() << "WorkThread() 线程ID " << QThread::currentThreadId();
}

void WorkThread::run() {

  qDebug() << "run 线程ID= " << QThread::currentThreadId();
  // 在run线程中创建的
  m_tcpClient = new QTcpSocket();
  m_tcpClient->setSocketDescriptor(m_socket);

  QString info = QString("客户端%1:%2连接成功!")
                     .arg(m_tcpClient->peerAddress().toString())
                     .arg(m_tcpClient->peerPort());
  emit showMessage(info, true);

  // 断开连接后的信号
  connect(m_tcpClient, SIGNAL(disconnected()), this, SLOT(onDisconnected()),
          Qt::DirectConnection);

  // 接收到数据的信号
  connect(m_tcpClient, SIGNAL(readyRead()), this, SLOT(onReadyRead()),
          Qt::DirectConnection);

  auto sendData = [this](const QByteArray &bf) {
    qDebug() << "接收数据 " << QThread::currentThreadId();
    m_tcpClient->write(bf);
  };

  // 这里this是主线程的对象，m_tcpClient是子线程的对象
  connect(this, &WorkThread::onSend, m_tcpClient, sendData,
          Qt::QueuedConnection);
  // 启动事件循环,否则信号槽不生效
  exec();

  // 关闭连接
  m_tcpClient->disconnectFromHost();
  // 销毁对象
  m_tcpClient->deleteLater();
  qDebug() << "线程结束了!";
}

void WorkThread::stopThread() {
  // 应该调用quit或者exit来退出事件循环
  exit(0);
}

void WorkThread::onDisconnected() {
  emit showMessage("连接被断开！", false);
  exit(0); // 退出循环
  emit onThreadStoped(this);
}

void WorkThread::onReadyRead() {
  qDebug() << "接收数据 " << QThread::currentThreadId();
  QByteArray data = m_tcpClient->readAll();
  QString str = QString("收到数据: %1").arg(QString(data));
  emit showMessage(str, true);
}

void WorkThread::send(const QByteArray &arr) {
  qDebug() << "发数据 " << QThread::currentThreadId();
  // m_tcpClient->write(arr);
  emit onSend(arr);
}
